package com.example.spring.jpa.specification;

import org.springframework.data.jpa.domain.Specification;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * @author: orange
 * @create: 2023-07-25 00:15
 * @description:
 */
public class SpecificationApplication<T> {
    private final AstRecursion<T> astRecursion;

    public SpecificationApplication(Class<?> eClass) {
        astRecursion = new AstRecursion<T>(eClass);
    }

    public Specification<T> specification(String exp) {
        return new Specification<T>() {
            @Override
            public Predicate toPredicate(Root<T> root,
                                         CriteriaQuery<?> query,
                                         CriteriaBuilder criteriaBuilder) {
                if (exp == null || exp.equals("")) return null;
                try {
                    astRecursion.setRoot(root);
                    astRecursion.setCriteriaQuery(query);
                    astRecursion.setCriteriaBuilder(criteriaBuilder);
                    return astRecursion.exec(exp);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        };
    }
}
